using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using WPF_MVVM_Test.MVVM_Model.Common;
using WPF_MVVM_Test.MVVM_Model.WorkOrderTask;

namespace WPF_MVVM_Test.Services
{
    /// <summary>
    /// 工单任务API服务类 - 对接真实的后端API
    /// </summary>
    public class WorkOrderTaskApiService : IDisposable
    {
        private readonly HttpClient _httpClient;
        private readonly JsonSerializerOptions _jsonOptions;
        private const string API_PATH = "api/WorkOrderTask";

        public WorkOrderTaskApiService()
        {
            _httpClient = new HttpClient();
            _httpClient.BaseAddress = new Uri("http://8.140.242.140:8888/");
            _httpClient.DefaultRequestHeaders.Add("Accept", "application/json");
            _httpClient.Timeout = TimeSpan.FromSeconds(30);

            _jsonOptions = new JsonSerializerOptions
            {
                PropertyNameCaseInsensitive = true,
                DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
                UnmappedMemberHandling = JsonUnmappedMemberHandling.Skip
            };
        }

        /// <summary>
        /// 获取工单任务分页列表
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">页大小</param>
        /// <returns></returns>
        public async Task<ApiResponse<PagedData<WorkOrderTaskApiModel>>> GetWorkOrderTaskPageAsync(int pageIndex = 1, int pageSize = 10)
        {
            try
            {
                var url = $"{API_PATH}/debug/simple-page?pageIndex={pageIndex}&pageSize={pageSize}";
                System.Diagnostics.Debug.WriteLine($"API请求URL: {_httpClient.BaseAddress}{url}");

                var response = await _httpClient.GetAsync(url);
                System.Diagnostics.Debug.WriteLine($"API响应状态: {response.StatusCode}");

                if (response.IsSuccessStatusCode)
                {
                    var jsonContent = await response.Content.ReadAsStringAsync();
                    System.Diagnostics.Debug.WriteLine($"API响应内容长度: {jsonContent?.Length ?? 0}");
                    System.Diagnostics.Debug.WriteLine($"API响应内容前500字符: {jsonContent?.Substring(0, Math.Min(500, jsonContent?.Length ?? 0))}");

                    var apiResponse = JsonSerializer.Deserialize<ApiResponse<PagedData<WorkOrderTaskApiModel>>>(jsonContent, _jsonOptions);
                    System.Diagnostics.Debug.WriteLine($"反序列化结果 - IsSuc: {apiResponse?.IsSuc}, Data项数: {apiResponse?.Data?.Data?.Count ?? 0}");
                    return apiResponse;
                }
                else
                {
                    return new ApiResponse<PagedData<WorkOrderTaskApiModel>>
                    {
                        IsSuc = false,
                        Code = (int)response.StatusCode,
                        Msg = $"请求失败: {response.ReasonPhrase}",
                        Data = null
                    };
                }
            }
            catch (Exception ex)
            {
                return new ApiResponse<PagedData<WorkOrderTaskApiModel>>
                {
                    IsSuc = false,
                    Code = -1,
                    Msg = $"请求异常: {ex.Message}",
                    Data = null
                };
            }
        }

        /// <summary>
        /// 单个报工
        /// </summary>
        /// <param name="request">报工请求数据</param>
        /// <returns></returns>
        public async Task<ApiResponse<object>> SubmitWorkReportAsync(WorkReportRequest request)
        {
            try
            {
                var url = $"{API_PATH}/batch-work-report";
                // 单个报工也使用批量接口，传入单个元素的数组
                var requestList = new List<WorkReportRequest> { request };
                var jsonContent = JsonSerializer.Serialize(requestList, _jsonOptions);
                var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");

                var response = await _httpClient.PostAsync(url, content);

                if (response.IsSuccessStatusCode)
                {
                    var responseContent = await response.Content.ReadAsStringAsync();
                    var apiResponse = JsonSerializer.Deserialize<ApiResponse<object>>(responseContent, _jsonOptions);
                    return apiResponse ?? new ApiResponse<object> { IsSuc = false, Msg = "响应解析失败" };
                }
                else
                {
                    return new ApiResponse<object>
                    {
                        IsSuc = false,
                        Code = (int)response.StatusCode,
                        Msg = $"报工失败: {response.ReasonPhrase}",
                        Data = null
                    };
                }
            }
            catch (Exception ex)
            {
                return new ApiResponse<object>
                {
                    IsSuc = false,
                    Code = -1,
                    Msg = $"报工异常: {ex.Message}",
                    Data = null
                };
            }
        }

        /// <summary>
        /// 批量报工
        /// </summary>
        /// <param name="requests">批量报工请求数据</param>
        /// <returns></returns>
        public async Task<ApiResponse<object>> SubmitBatchWorkReportAsync(List<WorkReportRequest> requests)
        {
            try
            {
                var url = $"{API_PATH}/batch-work-report";
                var jsonContent = JsonSerializer.Serialize(requests, _jsonOptions);
                var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");

                var response = await _httpClient.PostAsync(url, content);

                if (response.IsSuccessStatusCode)
                {
                    var responseContent = await response.Content.ReadAsStringAsync();
                    var apiResponse = JsonSerializer.Deserialize<ApiResponse<object>>(responseContent, _jsonOptions);
                    return apiResponse;
                }
                else
                {
                    return new ApiResponse<object>
                    {
                        IsSuc = false,
                        Code = (int)response.StatusCode,
                        Msg = $"批量报工失败: {response.ReasonPhrase}",
                        Data = null
                    };
                }
            }
            catch (Exception ex)
            {
                return new ApiResponse<object>
                {
                    IsSuc = false,
                    Code = -1,
                    Msg = $"批量报工异常: {ex.Message}",
                    Data = null
                };
            }
        }

        /// <summary>
        /// 将API模型转换为UI模型
        /// </summary>
        /// <param name="apiModel">API模型</param>
        /// <param name="index">索引</param>
        /// <returns></returns>
        public WorkOrderTaskModel ConvertToUIModel(WorkOrderTaskApiModel apiModel, int index)
        {
            return new WorkOrderTaskModel
            {
                Id = apiModel?.Id,
                Index = index,
                SequenceNumber = apiModel?.SequenceNumber,
                TaskNumber = apiModel?.TaskNumber,
                TaskName = apiModel?.TaskName,
                StationName = apiModel?.StationName,
                ProcessCode = apiModel?.ProcessCode,
                ProcessName = apiModel?.ProcessName,
                PlanStartTime = DateTime.TryParse(apiModel?.PlanStartTime, out var planStart) ? planStart : (DateTime?)null,
                PlanEndTime = DateTime.TryParse(apiModel?.PlanEndTime, out var planEnd) ? planEnd : (DateTime?)null,
                ActualStartTime = DateTime.TryParse(apiModel?.ActualStartTime, out var actualStart) ? actualStart : (DateTime?)null,
                ActualEndTime = DateTime.TryParse(apiModel?.ActualEndTime, out var actualEnd) ? actualEnd : (DateTime?)null,
                PlanQuantity = ConvertDecimalToInt(apiModel?.PlanQuantity),
                ActualQuantity = ConvertDecimalToInt(apiModel?.ActualQuantity),
                Status = apiModel?.Status ?? "未开工",
                Remarks = apiModel?.Remarks,
                PlanDuration = FormatDuration(apiModel?.PlanDuration),
                ActualDuration = FormatDuration(apiModel?.ActualDuration)
            };
        }

        /// <summary>
        /// 安全地将decimal转换为int，避免溢出异常
        /// </summary>
        private int? ConvertDecimalToInt(decimal? value)
        {
            if (!value.HasValue)
                return null;

            try
            {
                // 检查是否在int范围内
                if (value.Value > int.MaxValue)
                {
                    System.Diagnostics.Debug.WriteLine($"WorkOrderTaskService: 数量值 {value.Value} 超出int最大值，使用最大值 {int.MaxValue}");
                    return int.MaxValue;
                }
                if (value.Value < int.MinValue)
                {
                    System.Diagnostics.Debug.WriteLine($"WorkOrderTaskService: 数量值 {value.Value} 超出int最小值，使用最小值 {int.MinValue}");
                    return int.MinValue;
                }

                return (int)value.Value;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"WorkOrderTaskService: 转换数量值失败 {value.Value}: {ex.Message}，返回null");
                return null;
            }
        }

        /// <summary>
        /// 格式化时长显示
        /// </summary>
        private string? FormatDuration(decimal? duration)
        {
            if (!duration.HasValue)
                return null;

            var hours = (int)duration.Value;
            var minutes = (int)((duration.Value - hours) * 60);

            if (minutes > 0)
                return $"{hours}小时{minutes}分钟";
            else
                return $"{hours}小时";
        }

        /// <summary>
        /// 根据总体结果获取状态
        /// </summary>
        /// <param name="overallResult">总体结果</param>
        /// <returns></returns>
        private string GetStatusFromResult(string overallResult)
        {
            return overallResult switch
            {
                "合格" => "已完成",
                "不合格" => "已暂停",
                _ => "进行中"
            };
        }

        /// <summary>
        /// 单个派工
        /// </summary>
        /// <param name="taskId">任务ID</param>
        /// <param name="teamName">班组名称</param>
        /// <param name="supervisor">负责人</param>
        /// <param name="qualityDepartment">质量部门</param>
        /// <param name="qualityPersonnel">质量人员</param>
        /// <param name="otherMembers">其他成员</param>
        /// <param name="notes">备注</param>
        /// <returns></returns>
        public async Task<bool> DispatchAsync(string taskId, string teamName, string supervisor,
            string qualityDepartment, string qualityPersonnel, string otherMembers, string notes)
        {
            try
            {
                // 构建请求体 - 发送数组格式，单个任务ID
                var requestBody = new[]
                {
                    new
                    {
                        workOrderTaskEntityId = taskId,
                        teamName = teamName,
                        teamPrincipal = supervisor,
                        otherMembers = otherMembers,
                        qualityTestingDept = qualityDepartment,
                        qualityTestingPeople = qualityPersonnel,
                        remark = notes
                    }
                };

                var json = JsonSerializer.Serialize(requestBody);
                var content = new StringContent(json, Encoding.UTF8, "application/json");

                var response = await _httpClient.PostAsync("api/WorkOrderTask/batch-dispatch", content);

                if (response.IsSuccessStatusCode)
                {
                    var responseContent = await response.Content.ReadAsStringAsync();
                    var result = JsonSerializer.Deserialize<ApiResponse<object>>(responseContent, _jsonOptions);
                    return result?.IsSuc == true;
                }

                return false;
            }
            catch (Exception ex)
            {
                // 记录日志
                Console.WriteLine($"派工失败: {ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// 批量派工
        /// </summary>
        /// <param name="taskIds">任务ID数组</param>
        /// <param name="teamName">班组名称</param>
        /// <param name="supervisor">负责人</param>
        /// <param name="qualityDepartment">质量部门</param>
        /// <param name="qualityPersonnel">质量人员</param>
        /// <param name="otherMembers">其他成员</param>
        /// <param name="notes">备注</param>
        /// <returns></returns>
        public async Task<bool> BatchDispatchAsync(string[] taskIds, string teamName, string supervisor,
            string qualityDepartment, string qualityPersonnel, string otherMembers, string notes)
        {
            try
            {
                // 构建请求体 - 发送数组格式，多个任务ID用逗号分隔在单个对象中
                var requestBody = new[]
                {
                    new
                    {
                        workOrderTaskEntityId = string.Join(",", taskIds), // 多个ID用逗号分隔
                        teamName = teamName,
                        teamPrincipal = supervisor,
                        otherMembers = otherMembers,
                        qualityTestingDept = qualityDepartment,
                        qualityTestingPeople = qualityPersonnel,
                        remark = notes
                    }
                };

                var json = JsonSerializer.Serialize(requestBody);
                var content = new StringContent(json, Encoding.UTF8, "application/json");

                var response = await _httpClient.PostAsync("api/WorkOrderTask/batch-dispatch", content);

                if (response.IsSuccessStatusCode)
                {
                    var responseContent = await response.Content.ReadAsStringAsync();
                    var result = JsonSerializer.Deserialize<ApiResponse<object>>(responseContent, _jsonOptions);
                    return result?.IsSuc == true;
                }

                return false;
            }
            catch (Exception ex)
            {
                // 记录日志
                Console.WriteLine($"批量派工失败: {ex.Message}");
                return false;
            }
        }

        public void Dispose()
        {
            _httpClient?.Dispose();
        }
    }
}
